<template>
  <!--  个人信息修改和完善-->
  <div>
    <el-card shadow="hover">
      <el-form ref="userinfoform" label-position="right" :model="userinfoform" :rules="rules" label-width="100px" class="demo-ruleForm">
        <el-form-item label="你的名称：" label-width="120px" prop="name">
          <el-input v-model="userinfoform.name" />
        </el-form-item>
        <el-form-item label="来自哪里：" label-width="120px" prop="region">
          <el-select
            v-model="userinfoform.region"
            filterable
            remote
            reserve-keyword
            placeholder="请输入省会名称"
            :remote-method="remoteMethod"
            :loading="loading"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="活动爱好：" label-width="120px" prop="hobby">
          <el-tag
            v-for="tag in hobbyarr"
            :key="tag"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)"
          >
            {{ tag }}
          </el-tag>
          <el-input
            v-if="inputVisible"
            ref="saveTagInput"
            v-model="inputValue"
            class="input-new-tag"
            size="small"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          />
          <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 增添爱好</el-button>
        </el-form-item>
        <el-form-item label="性别：" label-width="120px" prop="gender">
          <el-radio-group v-model="userinfoform.gender">
            <el-radio value="男" style="color: dodgerblue" label="男"><i class="el-icon-male" /></el-radio>
            <el-radio value="女" style="color: red" label="女"><i class="el-icon-female" /></el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="个人邮箱：" label-width="120px" prop="emailSuffix">
          <el-input v-model="emailPerffix" placeholder="请输入邮箱前缀" class="input-with-select">
            <el-select slot="suffix" v-model="userinfoform.emailSuffix" style="position: relative;left: 5px" filterable default-first-option placeholder="请选择后缀">
              <el-option
                v-for="item in EmailSuffixlist"
                :key="item.key"
                :label="item.value"
                :value="item.value"
              />
            </el-select>
          </el-input>
        </el-form-item>
        <el-form-item label="个人联系方式：" label-width="120px" prop="phone">
          <el-input v-model="userinfoform.phone" />
        </el-form-item>
        <el-form-item label="个人说明：" label-width="120px" prop="memo">
          <el-input v-model="userinfoform.memo" type="textarea" />
        </el-form-item>
        <el-form-item label-width="120px">
          <el-button type="primary" @click="submitForm('userinfoform')">确认修改</el-button>
          <el-button @click="resetForm('userinfoform')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getUserCode } from '@/utils/auth'
const { getProvinces } = require('@/api/dicts')
export default {
  name: 'Account',
  props: {
    user: {
      type: Object,
      default: () => {
        return {
          name: '', // 个人账号
          usercode: '', // 个人账号编号
          username: '', // 用户个人名称
          gender: '', // 个人性别
          region: '', // 来自省会
          hobby: '', // 兴趣爱好
          phone: '', // 电话
          email: '', // 邮箱地址
          memo: '', // 个人说明
          avatar: '', // 头像地址
          roles: [], // 角色列表
          creatTime: '', // 数据创建时间
          updateTime: '' // 上次修改时间
        }
      }
    }
  },
  data() {
    return {
      loading: false, // 是否加载
      inputVisible: false, // 是否展示标签的输入框
      inputValue: '', // 存放新增标签输入框
      options: [], // 存放匹配的省会名称
      list: [],
      province: [], // 存放所有的省会集合
      userinfoform: {
        userCode: getUserCode(),
        name: this.user.username, // 姓名
        gender: this.user.gender, // 性别
        hobby: '', // 兴趣爱好
        region: this.user.region,
        phone: this.user.phone, // 电话
        email: '', // 邮箱
        memo: this.user.memo, // 个人说明
        emailSuffix: '' // 选择的邮箱地址后缀 例如 qq.com
      },
      EmailSuffixlist: [
        { key: '1', value: '@163.com' },
        { key: '2', value: '@126.com' },
        { key: '3', value: '@qq.com' },
        { key: '4', value: '@yahoo.com' },
        { key: '5', value: '@gmail.com' },
        { key: '6', value: '@hotmail.com' }
      ],
      hobbyarr: this.user.hobby.split(','), // 切分爱好字符串为数组
      emailPerffix: this.user.email.split('@')[0], // 获取邮箱前缀
      rules: { // 表单参数简单校验
        name: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入用户联系电话', trigger: 'blur' },
          { min: 5, max: 11, message: '长度在5-11个数字', trigger: ['blur', 'change'] }
        ],
        region: [
          { required: true, message: '请选择省会名称', trigger: 'blur' }
        ],
        emailPerffix: [
          { required: true, message: '请输入邮箱地址前缀', trigger: 'blur' }
        ],
        emailSuffix: [
          { required: false, message: '请选择邮箱地址后缀', trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请选择一个性别', trigger: 'blur' }
        ],
        memo: [
          { required: false, message: '请填写个人说明', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.getProvincesdata()
  },
  methods: {
    // 获取全部省会名称
    async getProvincesdata() {
      const res = await getProvinces()
      this.province = res.data.main
      this.list = this.province.map(item => {
        return { value: `${item.provinceId}`, label: `${item.provinceName}` }
      })
    },
    // 提交修改
    async submit() {
      const data = this.userinfoform
      console.log(data)
      const res = await this.$store.dispatch('user/modifyInfo', data)
      console.log(res)
      const { respCode } = res.respOutMsgHeader
      console.log(respCode)
      if (respCode === 200) {
        this.$message({
          type: 'success',
          message: '用户信息修改成功！',
          duration: 3 * 1000
        })
        this.$emit('reflushData') // 跳回主页
      } else {
        this.$message({
          type: 'error',
          message: '用户信息填写修改失败，检查是否正确提交，或刷新页面重试',
          duration: 5 * 1000
        })
      }
    },
    // 提交确认
    submitForm(formName) {
      const hobby_str = this.hobbyarr.join(',') // 数组转化成字符串
      this.userinfoform.hobby = hobby_str
      this.userinfoform.email = this.emailPerffix + this.userinfoform.emailSuffix // 拼接回邮箱地址
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //  加入修改api方法
          this.submit()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    // 删除爱好标签
    handleClose(tag) {
      this.hobbyarr.splice(this.hobbyarr.indexOf(tag), 1)
    },
    // 展示新增标签输入框
    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 新增标签内容检测
    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) { // 若输入了内容
        this.hobbyarr.push(inputValue) // 新增标签
      }
      this.inputVisible = false // 关闭输入框
      this.inputValue = '' // 默认值 ''
    },
    // 查询过滤器
    remoteMethod(query) {
      if (query !== '') {
        this.loading = true
        setTimeout(() => {
          this.loading = false
          this.options = this.list.filter(item => item.label.indexOf(query) !== -1)
        }, 200)
      } else {
        this.userinfoform.region = ''
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
